package com.ruoyi.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ruoyi.vo.User;
import com.ruoyi.mapper.LoginMapper;
import com.ruoyi.service.LoginService;
import com.ruoyi.utils.DuanxinUtils;
import com.ruoyi.utils.IdWorker;
import com.ruoyi.utils.JwtUtil;
import com.ruoyi.utils.Result;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginMapper loginMapper;

    @Resource
    private IdWorker idWorker;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Resource
    private RedisTemplate redisTemplate;




    public Result login(User user) {
        User dbUser=loginMapper.user(user);
        if (dbUser==null){

            return Result.error(20001,"用户名或密码错误");
        }
        if (!bCryptPasswordEncoder.matches(user.getPassword(),dbUser.getPassword())){

            return Result.error(20001,"用户名或密码错误");
        }

        String token = null;
        try {
            token = JwtUtil.sign(idWorker.nextId(),dbUser.getUsername(),"libb");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        redisTemplate.opsForValue().set(token,token,30, TimeUnit.MINUTES);
        return Result.success(token);
    }

    public Result sendCode(String mobile) {
        String redisCode = (String) redisTemplate.opsForValue().get(mobile);
        if (redisCode!=null){
            return Result.error(20002,"验证码以过期!");
        }
        String code = RandomUtil.randomNumbers(6);
        DuanxinUtils.sendDuanxin(mobile,code);
        redisTemplate.opsForValue().set(mobile,code,30, TimeUnit.MINUTES);
        return Result.success(code);
    }


    public Result loginMobile(User user){

        User dbUser= loginMapper.loginMobile(user);
        if (dbUser==null){

            return Result.error(20002,"手机号或验证码错误!");
        }
        String redisCode =(String) redisTemplate.opsForValue().get(user.getMobile());
        if (redisCode==null){

            return Result.error(20002,"验证码以过期!");
        }
        if (dbUser.equals(redisCode)){

            return Result.error(20002,"手机号或验证码错误!");
        }

        String token = null;
        try {
            token = JwtUtil.sign(idWorker.nextId(),dbUser.getMobile(),"libb");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        redisTemplate.opsForValue().set(token,token,30, TimeUnit.MINUTES);

        return Result.success(token);
    }
}
